clear all 
cd "~\Data\Open_Close_Auctions"

use auction_price_impact2021.dta, clear 

keep if year(date)>2011

merge 1:1 permno date using merged_permno_date_from_step2_sample_noAmex.dta

keep if _merge==3

sort permno date
by permno: gen ea_dummy_open=ea_dummy[_n-1]
xtset permno date


gen pct_oi=(close_imb_qty)/adv_10d
drop if pct_oi>10
* signed close oi 
gen signed_pct_oi1=pct_oi  if inlist(close_imb_side, "B")
replace signed_pct_oi1=-1*pct_oi if close_imb_side=="S"
replace signed_pct_oi1=0 if missing(signed_pct_oi1)
gen closing_auction_oib=signed_pct_oi1

gen signed_pct_open_oi=imbalance/adv_10d if inlist(imbalance_side, "B")
replace signed_pct_open_oi=-1*imbalance/adv_10d if inlist(imbalance_side, "S")
replace signed_pct_open_oi=0 if missing(signed_pct_open_oi)


gen abs_open_oib=abs(signed_pct_open_oi)
gen abs_close_oib=abs(closing_auction_oib)


gen subsample_group=1 if !missing(sp500_flag)
replace subsample_group=2 if missing(subsample_group) &  !missing(lag1_me) & lag1_me > me_cutoff50
replace subsample_group=3 if missing(subsample_group) & !missing(lag1_me) & lag1_me < me_cutoff50 & lag1_me > me_cutoff20
replace subsample_group=4 if missing(subsample_group) & !missing(lag1_me) & lag1_me < me_cutoff20




gen open_volume=osize/adv_10d
gen close_volume=csize/adv_10d
replace open_volume=0 if missing(osize)
replace close_volume=0 if missing(csize)

replace open_volume=. if open_volume>100 
replace close_volume=. if close_volume>100



* general trend;

collapse (mean) close_volume_mean=close_volume open_volume_mean=open_volume (median) close_volume_median=close_volume open_volume_median=open_volume,  by(date)
tsset date 
tssmooth ma close_volume_ma=close_volume_mean, window(180)
tssmooth ma open_volume_ma=open_volume_mean, window(180)

label var date "Date"
label var close_volume_mean "daily"
label var close_volume_ma "180-day moving average"

label var open_volume_mean "daily "
label var open_volume_ma "180-day moving average"

twoway line close_volume_mean date  , legend(position(6) rows(1)) ytitle("Closing Auction Volume as of 10-day ADV") 
twoway line close_volume_ma date , legend(position(6) rows(1)) ytitle("Moving Average") 


twoway line open_volume_mean date  , legend(position(6) rows(1)) ytitle("Opening Auction Volume as of 10-day ADV")  
twoway line open_volume_ma date  , legend(position(6) rows(1)) ytitle("Moving Average") 
